# coding=utf-8
import time

from django.db import models

from common.utils import location_convert


class BaseModel(models.Model):
    created_at = models.DateTimeField(u"创建时间", auto_now_add=True)
    updated_at = models.DateTimeField(u"最后修改时间", auto_now=True)


class UserDevice(BaseModel):
    user_id = models.CharField(u'手机ID', max_length=64)
    device_id = models.CharField(u"设备ID", max_length=64)
    alias = models.CharField(u"别名", max_length=64, null=True, default=None)
    heart_mode = models.BooleanField(u'心跳报警模式', default=False)
    location_mode = models.BooleanField(u'距离报警模式', default=False)

    def __unicode__(self):
        return '%s: %s' % (self.device_id, self.alias)

    class Meta:
        verbose_name = u"用户设备"
        verbose_name_plural = u"用户设备"


class DeviceData(BaseModel):
    """记录原始数据"""
    device_id = models.CharField(u"设备ID", max_length=64)
    beat = models.IntegerField(u"心跳", default=0)
    lac = models.CharField('lac', default='', max_length=64)
    ci = models.CharField('ci', default='', max_length=64)
    lon = models.CharField(u'经度', default='', max_length=16)
    lat = models.CharField(u'纬度', default='', max_length=16)
    radius = models.IntegerField(u'误差', default=0)
    address = models.CharField(u'位置', default='', max_length=128)
    timestamp = models.IntegerField(u'记录时间', default=None)

    class Meta:
        verbose_name = u"设备数据"
        verbose_name_plural = u"设备数据"
        ordering = ('timestamp',)

    def __unicode__(self):
        return self.device_id

    def to_dict(self):
        return {
            'device_id': self.device_id,
            'lon': self.lon,
            'lat': self.lat,
            'radius': self.radius,
            'address': self.address,
            'timestamp': self.timestamp,
            'beat': self.beat
        }

    def save(self, *args, **kwargs):
        print 'lac: %s, ci: %s' % (self.lac, self.ci)
        if self.lac and self.ci:
            data = location_convert(self.lac, self.ci)
            if data:
                self.lon = data['lon']
                self.lat = data['lat']
                self.radius = data['radius']
                self.address = data['address']
        super(BaseModel, self).save(*args, **kwargs)


class AvgHeartBeat(BaseModel):
    device_id = models.CharField(u"设备ID", max_length=64)
    beat = models.IntegerField(u"平均心跳", default=0)
    timestamp = models.DateTimeField(u"时间戳(分钟)")

    def __unicode__(self):
        return '%s >>> %s >>> %s' % (self.device_id, self.beat, self.minute)

    class Meta:
        verbose_name = u"平均心跳数据"
        verbose_name_plural = u"平均心跳数据"
